package cn.bestick.cblog.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import cn.bestick.cblog.dao.FriendLinkDao;
import cn.bestick.cblog.dmo.FriendLink;

public class FriendLinkDaoImpl extends BaseDao implements FriendLinkDao {
	Connection con = null;

	public List<FriendLink> all() throws Exception {
		con = getCon();

		List<FriendLink> friendLinks = new ArrayList<FriendLink>();
		String sql = "select * from t_friendlink";
		PreparedStatement pstmt = con.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		while (rs.next()) {
			FriendLink friendLink = new FriendLink();
			friendLink.setId(rs.getInt("friendLinkId"));
			friendLink.setTitle(rs.getString("title"));
			friendLink.setUrl(rs.getString("url"));
			friendLinks.add(friendLink);
		}

		close(con);
		return friendLinks;
	}

	public void update(FriendLink friendLink) throws Exception {
		con = getCon();

		String sql = "update t_friendlink set title=?,url=? where friendLinkId=?";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, friendLink.getTitle());
		pstmt.setString(2, friendLink.getUrl());
		pstmt.setInt(3, friendLink.getId());
		pstmt.executeUpdate();

		close(con);
	}

	public void save(FriendLink friendLink) throws Exception {
		con = getCon();

		String sql = "insert into t_friendlink values(null,?,?)";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, friendLink.getTitle());
		pstmt.setString(2, friendLink.getUrl());
		pstmt.executeUpdate();

		close(con);
	}

	public void delete(Integer id) throws Exception {
		con = getCon();

		String sql = "delete from t_friendlink where friendLinkId=?";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setInt(1, id);
		pstmt.executeUpdate();

		close(con);
	}

	public FriendLink get(Integer id) throws Exception {
		con = getCon();

		String sql = "select * from t_friendlink where friendLinkId=?";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setInt(1, id);
		ResultSet rs = pstmt.executeQuery();
		FriendLink friendLink = new FriendLink();
		if (rs.next()) {
			friendLink.setId(rs.getInt("friendLinkId"));
			friendLink.setTitle(rs.getString("title"));
			friendLink.setUrl(rs.getString("url"));
		}

		close(con);
		return friendLink;
	}

}
